package com.twu.biblioteca.persistences;

import com.twu.biblioteca.exceptions.BookNotFoundError;
import com.twu.biblioteca.models.Book;

import java.util.HashMap;

public class Books {
    private static Books rootInstance;
    private HashMap<Integer, Book> booksMap;

    public static void resetRootInstance(){
        rootInstance = null;
    }

    public static Books getRootInstance(){
        if (rootInstance == null){
            rootInstance = new Books();

            rootInstance.add(Book.createWithTitle("1984"));
            rootInstance.add(Book.createWithTitle("Catcher in the Rye"));
            rootInstance.add(Book.createWithTitle("Crouching Tiger, Hidden Dragon"));
            rootInstance.add(Book.createWithTitle("Domain Driven Design"));
        }
        return rootInstance;
    }

    protected Books(){
        booksMap = new HashMap<Integer, Book>();
    }

    protected Books(HashMap<Integer, Book> aBooksMap){
        booksMap = aBooksMap;
    }

    public void add(Book book){
        book.id = count();
        booksMap.put(book.id, book);
    }

    public Book find(Integer bookId) throws BookNotFoundError {
        if (!bookExists(bookId)){
            throw new BookNotFoundError(bookId);
        }
        return booksMap.get(bookId);
    }

    public int count(){
        return booksMap.size();
    }

    public boolean bookExists(Integer bookId){
        if (booksMap.containsKey(bookId)) {
            return true;
        } else {
            return false;
        }
    }

    public Books available(){
        HashMap<Integer, Book> filteredBookMap = new HashMap<Integer, Book>();

        for(Book book: booksMap.values()){
            if (!book.isBorrowed){
                filteredBookMap.put(book.id, book);
            }
        }

        Books filteredBooks = new Books(filteredBookMap);
        return filteredBooks;
    }

    public Books borrowed(){
        HashMap<Integer, Book> filteredBookMap = new HashMap<Integer, Book>();

        for(Book book: booksMap.values()){
            if (book.isBorrowed){
                filteredBookMap.put(book.id, book);
            }
        }

        Books filteredBooks = new Books(filteredBookMap);
        return filteredBooks;
    }

    public void print(){
        for(Book book: booksMap.values()){
            book.print();
        }
    }
}
